<?php
/**
 * 商品模型管理
 * @author cjli
 *
 */
class ProductModel extends Model
{
	/**
	 * 获取产品信息
	 * @param int $pid 产品ID号
	 * @return array
	 */
	public static function getProductInfo($pid)
	{
		$product_db = D('product');
		$info = $product_db->find($pid);
		if($info['restriction'] > 0)
			$info['style'] = 'display:block;';
		else
			$info['style'] = 'display:none;';
		return $info;
	}


	/**
	 * 获取商品信息
	 * @param int $pid 商品ID号
	 * @return array
	 */
	public static function get_product_info($pid, $lang_id=0)
	{
		if($lang_id){
			$language_id = $lang_id;
		}else{
			global $language_id;
		}
		$default_product_info = array();

		$cacheId = 'product_'.$pid.'_'.$language_id;
		if(S($cacheId)){
			$info = S($cacheId);
		}else{
			if(!$lang_id){
				$default_product_info = self::get_product_info($pid, C('language_id'));
			}
			$product_db = D('product');
			$where = array(
				'language_id' => $language_id ? $language_id : C('language_id'),
//				'display' => 1,
				'is_delete' => 0,
				'id' => $pid,
			);
			$product_db->join('product_items ON product_items.product_id = product.id');
			$info = $product_db->where($where)->find();

			if( !$info ){
				$info = $default_product_info;
			}
			if( !$info ){
				return false;
			}
			else{
				$info['name'] = $info['name'] ? $info['name'] : (isset($default_product_info['name']) && $default_product_info['name'] ? $default_product_info['name'] : '');
				$info['description'] = $info['description'] ? $info['description'] : (isset($default_product_info['description']) && $default_product_info['description'] ? $default_product_info['description'] : '');
				$where_attr = array('product_id'=>$pid,'language_id'=>1);
				$product_items_info = D('product_items')->where($where_attr)->find();
				$info['english_name'] = $product_items_info['name'];
				$info['url'] = U('/product/'.$pid.'-'.generateUrl_un($product_items_info['name']));
				//$info['url'] = U('/product/'.$pid.'-'.str_replace(' ','-',($info['name'])));
				// if($info['two_suit_sn']){//三件套与两件套关联
				// 	$two_suit_info = ProductModel::get_product_info($info['two_suit_sn']);
				// 	if($two_suit_info){
				// 		 $info['two_suit_info'] = $two_suit_info;
				// 	}
				// }
				//检测是否是3d搭配产品
				$info['suppliers_name'] = '';
				$info['3d_show2'] = false;
				$info['eng_id']=$info['eng_id']?$info['eng_id']:0;
				$imgPathRoot = '/data/show2/'; //图片存储目录
				if(is_dir('.'.$imgPathRoot.$info['eng_id'])){
					$info['3d_show2']=true;
				}

			}
			$parentid = CategoryModel::get_category_parentid($info['catid']);
			$info['cat_one_id'] = $parentid>0 ? $parentid : $info['catid'];
			//获取购买该产品的数量(已付定金的)
			/*$orders_db = D('orders');
			$orders_db->field('sum(orders_items.qty) as number');
			$orders_db->join('orders_items ON orders_items.order_id = orders.id');
			$number= $orders_db->where('orders_items.product_id='.$pid.' AND orders.payment_status=1')->find();
			$info['number'] = $number['number'];
			if(!$info['number']){
				$info['number'] = 1;
			}*/

			S($cacheId, $info);
		}
		return $info;
	}

	/**
	 * 获取产品详细内容
	 * @param int $pid 商品ID号
	 * @param int $language_id 语言ID
	 */
	public static function get_product_items($pid, $language_id)
	{
		$product_items_id = D('product_items');
		$info = $product_items_id->field('product_id,lanauge_id', true)->where(array('product_id' => $pid, 'language_id' => $language_id))->find();
		return $info;
	}

	/**
	 * 商品关联图片
	 * @param int $pid 商品ID
	 */
	public static function get_product_photo_list($pid,$did=0)
	{
		$product_photo_db = D('product_photo');
		if($did>0){
			$files = $product_photo_db->field('product_photo.*')->join('product_photo_relation AS pr ON pr.fid = product_photo.fid')->where('pr.did='.$did)->order('product_photo.order ASC,product_photo.fid ASC')->select();
		}else{
			$files = $product_photo_db->field('product_photo.*')->join('product_photo_relation AS pr ON pr.fid = product_photo.fid')->where('pr.pid='.$pid)->order('product_photo.order ASC,product_photo.fid ASC')->select();
		}

		if($files){
			foreach ($files as &$file){
				if(empty($file['thumb'])){
					$file['thumb'] = dirname($file['img']).'/thumb_'.basename($file['img']);
				}
			}
			unset($file);
		}
		return $files;
	}

	/**
	 * 产品背景图片
	 * @param int $pid 产品ID
	 */
	public static function get_product_background_photo_list($pid)
	{
		$product_photo_db = D('product_background_photo');
		$files = $product_photo_db->where('pid='.$pid)->select();
		return $files;
	}

	/**
	 * 获取商品关联属性列表
	 * @param int $pid 商品ID号
	 * @return array
	 */
	public static function get_product_relation_attribte_list($pid, $filter = array(),$did=0)
	{
		$pid = intval($pid);
		if(!$did){
			if(!$pid){
				return false;
			}
			$where = array('pa.product_id' => $pid);
		}else{
			$where = array('pa.designer_id' => $did);
		}

		if($filter){
			foreach ($filter as $key => $val){
				if(! is_null($val)){
					$where[$key] = $val;
				}
			}
		}
		$attribute_db = D('attribute');

		$attribute_db->field('attribute.attr_id, attribute.attr_name, attribute.attr_sell,pa.attr_value_id, pa.attr_value,pa.attr_price,pa.product_attr_id,av.attr_value AS attr_name_value,av.attr_img,pa.is_default');
		$attribute_db->join('product_attribute AS pa ON attribute.attr_id=pa.attr_id');
		$attribute_db->join('attribute_values AS av ON av.id = pa.attr_value_id');
		$attribute_db->where($where);
		$attribute_db->order('attribute.sort_order,pa.product_attr_id');
		$result = $attribute_db->select();
//		echo $attribute_db->getLastSql();exit;
		if($result){
			$attributes = array();

			foreach ($result as $attr)
			{
				$is_default = 0;
				if($attr['is_default']==$attr['attr_value_id']){
					$is_default = $attr['product_attr_id'];
				}

				if($attr['attr_value_id'] && empty($attr['attr_value'])){
					$attr['attr_value'] = $attr['attr_name_value'];
				}
				if ($attr['attr_sell'] == 0)
				{
					$arr['pro'][$attr['attr_id']]['name']  = $attr['attr_name'];
					$arr['pro'][$attr['attr_id']]['value'] = $attr['attr_value'];
				}
				else
				{
					$arr['spe'][$attr['attr_id']]['attr_type'] = $attr['attr_type'];
					$arr['spe'][$attr['attr_id']]['name']     = $attr['attr_name'];
					$arr['spe'][$attr['attr_id']]['values'][] = array(
						'label'        => $attr['attr_value'],
						'price'        => $attr['attr_price'],
						'format_price' => currency(abs($attr['attr_price'])),
						'image'					=> $attr['attr_img'],
						'id'           => $attr['product_attr_id'],
					);
					if($is_default){
						$arr['spe'][$attr['attr_id']]['default']     = $is_default;
					}
				}
			}
		}
		return isset($arr) ? $arr : null;
	}

	/**
	 * 获取商品定制关联属性列表
	 * @param int $pid 商品ID号
	 * @return array
	 */
	public static function get_product_custom_attribte_list($pid, $filter = array(),$language_id=1)
	{
		$pid = intval($pid);
		if(!$pid){
			return false;
		}
		$where = array(
			'pa.product_id' => $pid,
			'attribute_items.language_id' => $language_id,
			'is_hiden'=>0,
		);
		if($filter){
			foreach ($filter as $key => $val){
				if(! is_null($val)){
					$where[$key] = $val;
				}
			}
		}

		/*if($custom_id){
			$where = 'pa.product_id = '.$pid.' and attr_sell = '.$where['attr_sell'].' and (attr_advanced = '.$where['attr_advanced'].' or attr_advanced = 2)';
		}*/
		//$where = 'pa.product_id = '.$pid.' and attr_sell = '.$where['attr_sell'].'';

		$attribute_db = D('attribute');

		$attribute_db->field('attribute.sort_order as attr_sort_order,av.is_down as is_down,av.sort_order as av_sort_order,attribute.attr_custom,attribute.attr_pro_sort,attribute.attr_pro_type,attribute.attr_pro_fid,attribute.size_type,attribute.attr_id,attribute.attr_sell,attribute.attr_group,attribute.attr_type,attribute.attr_input_type,attribute.issd as attr_issd,attribute.is_show_sd as is_show_sd,attribute.is_monogram as is_monogram,pa.attr_value_id, pa.attr_value,pa.attr_price,pa.product_attr_id,av.issd as attr_value_issd,attribute.desc_name,av.desc_name as desc_name_values,av.attr_img,av.attr_img2,av.libu_img,av.add_money,pa.is_default,attribute_items.*,attribute.is_ll');
		$attribute_db->join('product_attribute AS pa ON attribute.attr_id=pa.attr_id');
		$attribute_db->join('attribute_values AS av ON av.id = pa.attr_value_id');
		$attribute_db->join('attribute_items ON attribute_items.attribute_id = attribute.attr_id');
		$attribute_db->where($where);
		//$attribute_db->order('attribute.attr_id,pa.product_attr_id');
		$attribute_db->order('attribute.attr_custom DESC,attribute.sort_order ASC, av.sort_order ASC, attribute.attr_id ASC');
		$result = $attribute_db->select();
		//echo $attribute_db->getLastSql();exit;

		if($result){
			$attributes = array();

			$option_default = '';
			foreach ($result as $attr)
			{
				$is_default = 0;
				if($attr['is_default']==$attr['attr_value_id']){
					$is_default = $attr['product_attr_id'];
				}
				if($attr['attr_value_id']){
					$attribute_values_items_db = D('attribute_values_items');
					$attribute_values_items = $attribute_values_items_db->where(array('att_value_id' => $attr['attr_value_id'],'language_id' => $language_id))->find();
					$attr['attr_value'] = $attribute_values_items['attr_value'];
					$attr['attr_name_value'] = $attribute_values_items['attr_value'];
					$attr['attr_content'] = $attribute_values_items['attr_content'];

				}

				if($attr['attr_value_id'] && empty($attr['attr_value'])){
					$attr['attr_value'] = $attr['attr_name_value'];
				}

				$arr[$attr['attr_id']]['attr_id'] = $attr['attr_id'];
				$arr[$attr['attr_id']]['name']     = $attr['name'];
				//$arr[$attr['attr_id']]['attr_type']     = $attr['attr_type'];
				$arr[$attr['attr_id']]['attr_content']     = $attr['attr_content'];
				//$arr[$attr['attr_id']]['attr_input_type'] = $attr['attr_input_type'];
				//$arr[$attr['attr_id']]['sort_order'] = $attr['attr_sort_order'];
				$arr[$attr['attr_id']]['attr_pro_type'] = $attr['attr_pro_type'];
				$arr[$attr['attr_id']]['attr_pro_fid'] = $attr['attr_pro_fid'];
				$arr[$attr['attr_id']]['attr_pro_sort'] = $attr['attr_pro_sort'];
				//$arr[$attr['attr_id']]['attr_help'] = AttributeModel::attribute_info($attr['attr_id']);
				$arr[$attr['attr_id']]['attr_custom'] = $attr['attr_custom'];
				$arr[$attr['attr_id']]['size_type'] = $attr['size_type'];
				$arr[$attr['attr_id']]['issd'] = $attr['attr_issd'];
				$arr[$attr['attr_id']]['is_ll'] = $attr['is_ll'];
				$arr[$attr['attr_id']]['is_show_sd'] = $attr['is_show_sd'];
				$arr[$attr['attr_id']]['is_monogram'] = $attr['is_monogram'];
				$arr[$attr['attr_id']]['desc_name'] = $attr['desc_name'];
				$arr[$attr['attr_id']]['values'][] = array(
					'label'        => $attr['attr_value'],
					'image'			=> $attr['attr_img'],
					'image2'		=> $attr['attr_img2'],
					'product_attr_id' => $attr['product_attr_id'],
					'attr_value_id' => $attr['attr_value_id'],
					'attr_content' => $attr['attr_content'],
					'sort_order' => $attr['av_sort_order']+100,
					'issd' => $attr['attr_value_issd'],
					'libu_img'=>$attr['libu_img'],
					'add_money'=>$attr['add_money'],
					'is_down'=>$attr['is_down'],
					'desc_name'=>$attr['desc_name_values'],
					'relate'=>$attr['relate'],
				);
				if($is_default){
					$arr[$attr['attr_id']]['default']     = $is_default;
					//给option里的attr_pro_type=3（颜色选项）使用,如default被清值后，用s_default做选中判断
					$arr[$attr['attr_id']]['s_default']   = $is_default;
				}
				//去掉绣字的默认值
				if($attr['attr_pro_type'] == 1||$attr['attr_pro_type'] == 10){
					$arr[$attr['attr_id']]['default'] = '';
				}

				if(in_array($attr['attr_id'], array(54,70,112,134))){
					//option多选
					if($attr['is_default']==$attr['attr_value_id']){
						$option_default .= $option_default ? '|'.$attr['product_attr_id'] : $attr['product_attr_id'];
					}

					// $yjxk = array(668,783,791,744,800,497,667,784,792,745,801,498,741,807); //特殊需要开圆角袖口的商品id
					// if(in_array($pid, $yjxk)){
					//  if(in_array($attr['attr_value_id'], array(762,765,761))){ //开圆角袖口
					//         $option_default .= $option_default ? '|'.$attr['product_attr_id'] : $attr['product_attr_id'];
					//  }
					// }

					// if(in_array($attr['attr_value_id'], array(133,136,210,340,342,642))){
					//  if(in_array($pid, $yjxk)){
					//  	if(!in_array($attr['attr_value_id'], array(136,342,210)))   //圆角袖口 和 Real Sleeve Slit 互斥
					//          $option_default .= $option_default ? '|'.$attr['product_attr_id'] : $attr['product_attr_id'];
					//  }else{
					//      $option_default .= $option_default ? '|'.$attr['product_attr_id'] : $attr['product_attr_id'];
					//  }
					// }

					// $kjfb = array(848,847);//裤脚翻边 商品id
					// if(in_array($pid, $kjfb) && in_array($attr['attr_value_id'], array(131,338))){
					//  $option_default .= $option_default ? '|'.$attr['product_attr_id'] : $attr['product_attr_id'];
					// }

					// $pjd = array(877,878,834,835,836,838);//票据袋 商品id
					// if(in_array($pid, $pjd) && in_array($attr['attr_value_id'], array(209,273,345))){
					//  $option_default .= $option_default ? '|'.$attr['product_attr_id'] : $attr['product_attr_id'];
					// }

					if($option_default) $arr[$attr['attr_id']]['default'] = $option_default;
				}

			}
		}
		return isset($arr) ? $arr : null;
	}

	/**
	 * 更新商品库存
	 * @param int $pid 商品ID号
	 * @param int $num 数量
	 */
	public static function update_product_stock($pid, $num)
	{
		$product_db = D('product');
		$product_db->where('id='.$pid)->setInc('stock', $num);
	}

	/**
	 * 获取商品库存
	 * @param int $pid 商品ID号
	 */
	public static function get_product_stock($pid)
	{
		$product_db = D('product');
		$stock = $product_db->where( array('id' => $pid) )->getField('stock');
		return $stock;
	}

	/**
	 * 获取产品积分
	 * @param int $pid 商品ID号
	 */
	public static function get_product_integral($pid)
	{
		$product = self::get_product_info($pid);
		if($product){
			$rank_integral = $product['rank_integral'] == -1 ? $product['sell_price'] : intval($product['rank_integral']);
			$integral = $product['integral'] == -1 ? $product['sell_price'] : intval($product['integral']);
			return array($rank_integral, $integral);
		}
		return false;
	}

	/**
	 * 获取商品总数量
	 * @param array $where	查询条件
	 */
	public static function get_product_count($post = array(),$where2="",$category=0)
	{
		global $language_id;

		$product_db = D('product');
		//商品分类
		$cat_id = isset($post['catid']) ? intval($post['catid']) : null;

		if($post['catids']){
			$catids = explode('_', $post['catids']);

			$cids_value = '';
			foreach ($catids as $cids){

				if($cids_value == ''){
					$categoryInfo = CategoryModel::get_category_info($cids);
					//dump($categoryInfo);exit;
					if(!$categoryInfo){
						$cids_value = null;
					}
					//获取子类集
					$cids_value = CategoryModel::get_category_child_ids($cids);
				}else{
					$cids_value .= ','.CategoryModel::get_category_child_ids($cids);
				}
			}
		}else{
			if($cat_id){
				$categoryInfo = CategoryModel::get_category_info($cat_id);
				if(!$categoryInfo){
					$cat_id = null;
				}
				//获取子类集
				if($cat_id){
					$cat_id = CategoryModel::get_category_child_ids($cat_id);
				}
			}
		}

		$recommend_id = isset($post['rid']) ? intval($post['rid']) : null;
		//筛选条件
		$where = array(
			'product.is_delete' => array('eq',0),
//			'product.sell_price' => array('gt', 0),
			'product.display' => isset($post['display']) ? intval($post['display']) : array('egt',1),
			'product.is_sell' => isset($post['is_sell']) ? intval($post['is_sell']) : null,
			'product.brand_id' => isset($post['bid']) ? intval($post['bid']) : null,
			'product.sn' => isset($post['sn']) ?  trim($post['sn']) : null,
			'product.designer_id' =>isset($post['designer_id']) ? intval($post['designer_id']) : null,
			'product.new_product' => isset($post['new_product']) ? intval($post['new_product']) : null,
		);
		foreach ($where as $key => $val){
			if(empty($val) && is_null($val)) unset($where[$key]);
		}
		if($cids_value){
			$map['product.catid'] = array('IN', $cids_value);
			//多分类扩展
			$pids = self::get_other_cat_pids($cids_value);
			if($pids){
				$map['_logic'] = 'OR';
				$map['product.id'] = array('IN', $pids);
			}
			$where['_complex'] = $map;
		}
		if($cat_id){
			$map['product.catid'] = array('IN', $cat_id);
			//多分类扩展
			$pids = self::get_other_cat_pids($cat_id);
			if($pids){
				$map['_logic'] = 'OR';
				$map['product.id'] = array('IN', $pids);
			}
			$where['_complex'] = $map;
		}

		//搜索名称  面料  ID
		if(isset($post['keyword']) && !empty($post['keyword'])){
			if(intval($post['keyword']) &&  is_numeric($post['keyword'])){
				$where2.= 'product.id='.intval($post['keyword']);
			}else{

				if($category==1){
					$where2.=" and ";
				}
				$where2.= ' product_items.name LIKE "%' . $post['keyword'] . '%"';

				$suppliers = D("suppliers")->where(array("suppliers_name"=> strtoupper(trim($post['keyword']))))->find();
				if($suppliers){
					$where2.= ' or product.suppliers_id =' . $suppliers['suppliers_id'];
				}
				$where['product_items.language_id'] = $language_id;
				$product_db->join('product_items ON product_items.product_id = product.id');
			}

		}
		//推荐
		if($recommend_id){
			$where['category_product.catid'] = $recommend_id;
			$product_db->join('category_product ON category_product.pid = product.id');
		}


		//属性查询
		if(isset($post['attr']) && $post['attr']){
			$filter_attr_array = self::get_filter_attr($post['attr']);
			if($filter_attr_array){
				$key=0;
				foreach ($filter_attr_array as $attr_id => $attrValues)
				{
					$where['pa'.$key.'.attr_id'] = $attr_id;
					if($attrValues['attr_value_id']){
						$where['pa'.$key.'.attr_value_id'] = $attrValues['attr_value_id'];
					}else{
						$where['pa'.$key.'.attr_value'] = $attrValues['attr_value'];
					}
					$product_db->join('product_attribute AS pa'.$key.' ON pa'.$key.'.product_id=product.id');
					$key++;
				}
				unset($key);
			}
		}
		//价格过滤
		if(isset($post['price']) && $post['price']){
			$priceArray = explode('_', $post['price']);
			foreach ($priceArray as $key => $pric){
				if(!is_numeric($pric)){
					unset($priceArray[$key]);
				}
			}
			if(is_array($priceArray)){
				$where['product.sell_price'] = array('gt', $priceArray[0]);
				if($priceArray[1]){
					$where['product.sell_price'] = array(array('gt', $priceArray[0]),array('lt', $priceArray[1]), 'AND');
				}
			}
		}

		//类型属性搜索
		$sc_value = 0;
		if(isset($post['style']) && !empty($post['style'])){
			$styleArray = explode('_', $post['style']);
			$productDb = D('product');
			$productDb->field('id');
			$productDb->where($where);
			$productList = $productDb->select();
			foreach($styleArray as $style){
				foreach($productList as $product){
					$productDb2 = D('product');
					$productInfo = $productDb2->field('id,category_id')->where('id='.$product['id'])->find();
					$categoryIds = explode(',', $productInfo['category_id']);
					if(in_array($style,$categoryIds)){
						$style_ids[$product['id']] = $product['id'];
					}
				}
			}
			$sc_value = 1;
		}
		//类型属性（颜色）搜索
		if(isset($post['colour']) && !empty($post['colour'])){
			$colourArray = explode('_', $post['colour']);
			if($sc_value == 1){
				foreach($colourArray as $colour){
					foreach($style_ids as $product){
						$productDb = D('product');
						$productInfo = $productDb->field('id,colour_id')->where('id='.$product)->find();
						$colourIds = explode(',', $productInfo['colour_id']);
						if(in_array($colour,$colourIds)){
							$colour_ids[$product] = $product;
						}
					}
				}
			}else{
				$productDb = D('product');
				$productDb->field('id');
				$productDb->where($where);
				$productList = $productDb->select();
				foreach($colourArray as $colour){
					foreach($productList as $product){
						$productDb2 = D('product');
						$productInfo = $productDb2->field('id,colour_id')->where('id='.$product['id'])->find();
						$colourIds = explode(',', $productInfo['colour_id']);
						if(in_array($colour,$colourIds)){
							$colour_ids[$product['id']] = $product['id'];
						}
					}
				}
			}
			$sc_value = 2;
		}
		if($sc_value >0){
			if($sc_value == 1){
				$count = count($style_ids);
			}elseif($sc_value == 2){
				$count = count($colour_ids);
			}
		}else{
			$product_db->where($where);
			if($where2){
				$product_db->where($where2);
			}
			$count = $product_db->count();
			//echo $product_db->getLastSql();//exit;
		}
		return $count;
	}

	/**
	 * 获取查询商品所在分类
	 * @param array $where	查询条件
	 */
	public static function get_product_search_category($post = array())
	{
		global $language_id;

		$product_db = D('product');
		//筛选条件
		$where = array(
			'product.is_delete' => array('eq',0),
//			'product.sell_price' => array('gt', 0),
			'product.display' => isset($post['display']) ? intval($post['display']) : array('egt',1),
			'product.is_sell' => isset($post['is_sell']) ? intval($post['is_sell']) : null,
			'product.brand_id' => isset($post['bid']) ? intval($post['bid']) : null,
			'product.sn' => isset($post['sn']) ?  trim($post['sn']) : null,
			'product.designer_id' =>isset($post['designer_id']) ? intval($post['designer_id']) : null,
		);
		foreach ($where as $key => $val){
			if(is_null($val)) unset($where[$key]);
		}

		if(isset($post['keyword']) && !empty($post['keyword'])){
			//用空格分割关键词
			$searchKeyword = trim($post['keyword']);
			$searchKeyword = explode(' ', $searchKeyword);
			$where_search_str = '';
			foreach ($searchKeyword as $searchVal) {
				if($searchVal){
					$where_search_str .= ' product_items.name LIKE "%' . $searchVal . '%" or';
				}
			}
			if($where_search_str){
				$where_search_str = trim($where_search_str, 'or');
				$where['_string'] = $where_search_str;
			}
			$where['product_items.language_id'] = $language_id;
			$product_db->join('product_items ON product_items.product_id = product.id');
		}
		$product_db->field('product.catid, COUNT( product.catid) AS number');
		$product_db->where($where);
		$product_db->group('product.catid');
		$categorys = $product_db->cache(true,C('DB_CACHE_TIME'))->select();
//		echo $product_db->getLastSql();exit;
		return $categorys;
	}

	/**
	 * 属性查询分析
	 * @param string $attr 属性post过滤条件
	 */
	public static function get_filter_attr($attr_post)
	{
		$attr_array = array();
		if($attr_post){
			$filter_attr_array = explode('.', $attr_post);
			foreach ($filter_attr_array as $key => $attr_id){
				if($attr_id==0)unset($filter_attr_array[$key]);
			}
			if($filter_attr_array){
				$product_attribute_db = D('product_attribute');
				foreach ($filter_attr_array as $key => $goods_id){
					$product_attribute_db->field('attr_id,attr_value_id,attr_value');
					$product_attribute_db->where('product_attr_id='.$goods_id);
					$product_attr = $product_attribute_db->cache(true, C('DB_CACHE_TIME'))->find();
					if($product_attr){
						$attr_array[$product_attr['attr_id']] = array(
							'attr_value_id' => $product_attr['attr_value_id'],
							'attr_value' => $product_attr['attr_value'],
						);
					}
				}
			}
		}
		return $attr_array;
	}

	/**
	 * 获取商品列表
	 * @param array $post 筛选条件
	 * @param int $firstRow 从第几个开始
	 * @param int $listRows	共取几个
	 */
	public static function get_product_list($post = array(), $firstRow = null, $listRows = 20 ,$yushou=0)
	{
		global $language_id;

		//商品分类
		$cat_id = isset($post['catid']) ? intval($post['catid']) : null;

		if($post['catids']){

			$catids = explode('_', $post['catids']);

			$cids_value = '';

			foreach ($catids as $cids){

				if($cids_value == ''){

					$categoryInfo = CategoryModel::get_category_info($cids);

					if(!$categoryInfo){

						$cids_value = null;
					}
					//获取子类集
					$cids_value = CategoryModel::get_category_child_ids($cids);

				}else{
					$cids_value .= ','.CategoryModel::get_category_child_ids($cids);

				}
			}

		}else{
			if($cat_id){

				$categoryInfo = CategoryModel::get_category_info($cat_id);

				if(!$categoryInfo){

					$cat_id = null;
				}
				//获取子类集
				if($cat_id){
					//dump($cat_id);die;
					$cat_id = CategoryModel::get_category_child_ids($cat_id);
				}
			}
		}

		$recommend_id = isset($post['rid']) ? intval($post['rid']) : null;
		//筛选条件
		$where = array(
			'product.is_delete' => array('eq',0),
//			'product.sell_price' => array('gt', 0),
			'product.display' => isset($post['display']) ? intval($post['display']) : array('egt',1),
			'product.is_sell' => isset($post['is_sell']) ? intval($post['is_sell']) : null,
			'product.brand_id' => isset($post['bid']) ? intval($post['bid']) : null,
			'product.sn' => isset($post['sn']) ?  trim($post['sn']) : null,
			'product.designer_id' =>isset($post['designer_id']) ? intval($post['designer_id']) : null,
			'product.new_product' => isset($post['new_product']) ? intval($post['new_product']) : null,
		);

		foreach ($where as $key => $val){
			if(empty($val) && is_null($val)) unset($where[$key]);
		}

		if($cids_value){
			$map['product.catid'] = array('IN', $cids_value);
			//多分类扩展
			$pids = self::get_other_cat_pids($cids_value);
			if($pids){
				$map['_logic'] = 'OR';
				$map['product.id'] = array('IN', $pids);
			}
			$where['_complex'] = $map;
		}
		if($cat_id){
			$map['product.catid'] = array('IN', $cat_id);
			//多分类扩展
			$pids = self::get_other_cat_pids($cat_id);
			if($pids){
				$map['_logic'] = 'OR';
				$map['product.id'] = array('IN', $pids);
			}
			$where['_complex'] = $map;
		}

		$product_db = D('product');

		//属性过滤
		if(isset($post['attr']) && $post['attr']){
			$filter_attr_array = self::get_filter_attr($post['attr']);
			if($filter_attr_array){
				$key=0;
				foreach ($filter_attr_array as $attr_id => $attrValues)
				{
					$where['pa'.$key.'.attr_id'] = $attr_id;
					if($attrValues['attr_value_id']){
						$where['pa'.$key.'.attr_value_id'] = $attrValues['attr_value_id'];
					}else{
						$where['pa'.$key.'.attr_value'] = $attrValues['attr_value'];
					}
					$product_db->join('product_attribute AS pa'.$key.' ON pa'.$key.'.product_id=product.id');
					$key++;
				}
				unset($key);
			}
		}

		//价格过滤
		if(isset($post['price']) && $post['price']){
			$priceArray = explode('_', $post['price']);
			foreach ($priceArray as $key => $pric){
				if(!is_numeric($pric)){
					unset($priceArray[$key]);
				}
			}
			if(is_array($priceArray)){
				$where['product.sell_price'] = array('gt', $priceArray[0]);
				if($priceArray[1]){
					$where['product.sell_price'] = array(array('gt', $priceArray[0]),array('lt', $priceArray[1]), 'AND');
				}
			}
		}

		$productList = array();
		$product_db->field('product.id');


		//用空格分割关键词  搜索
		if(isset($post['keyword']) && !empty($post['keyword'])){
			if(intval($post['keyword']) && is_numeric($post['keyword'])){
				$where['product.id'] =intval($post['keyword']);
			}else{
				$where3 = ' product_items.name LIKE "%' .$post['keyword'] . '%"';
				$suppliers = D("suppliers")->where(array("suppliers_name"=> strtoupper(trim($post['keyword']))))->find();
				if($suppliers){
					$where3.= ' or product.suppliers_id =' . $suppliers['suppliers_id'];
				}
				$product_db->where($where3);
			}
			$where['product_items.language_id'] = $language_id;
			$product_db->join('product_items ON product_items.product_id = product.id');
		}

		//关联推荐分类
		if($recommend_id){
			$where['category_product.catid'] = $recommend_id;
			$product_db->join('category_product ON category_product.pid = product.id');
		}
		//过滤分类不展示的 商品
		//$where['category.display'] = 1;

		$product_db->join('category ON category.id = product.catid');
		$product_db->where($where);


		//排序
		if (isset($post['orderby']) && $post['orderby']) {
			$product_db->order($post['orderby']);
		} else {
			$product_db->order('new_product desc,product.sorts asc, product.id DESC');
		}
		if (isset($firstRow)) {
			$product_db->limit($firstRow, $listRows);
		}
		$product_db->group('product.id');
		$productList = $product_db->cache(true,C('DB_CACHE_TIME'))->select();



		//类型属性搜索
		$sc_value = 0;
		if(isset($post['style']) && !empty($post['style'])){
			$styleArray = explode('_', $post['style']);
			foreach($styleArray as $style){
				foreach($productList as $product){

					$productDb = D('product');
					$productInfo = $productDb->field('id,category_id')->where('id='.$product['id'])->find();
					$categoryIds = explode(',', $productInfo['category_id']);
					if(in_array($style,$categoryIds)){
						$style_ids[$product['id']] = $product['id'];
					}
				}
			}
			$sc_value = 1;
		}
		//类型属性（颜色）搜索
		if(isset($post['colour']) && !empty($post['colour'])){
			$colourArray = explode('_', $post['colour']);
			if($sc_value == 1){
				foreach($colourArray as $colour){
					foreach($style_ids as $product){
						$productDb = D('product');
						$productInfo = $productDb->field('id,colour_id')->where('id='.$product)->find();
						$colourIds = explode(',', $productInfo['colour_id']);
						if(in_array($colour,$colourIds)){
							$colour_ids[$product] = $product;
						}
					}
				}
			}else{
				foreach($colourArray as $colour){
					foreach($productList as $product){
						$productDb = D('product');
						$productInfo = $productDb->field('id,colour_id')->where('id='.$product['id'])->find();
						$colourIds = explode(',', $productInfo['colour_id']);
						if(in_array($colour,$colourIds)){
							$colour_ids[$product['id']] = $product['id'];
						}
					}
				}
			}
			$sc_value = 2;
		}
		if($sc_value >0){
			if($sc_value == 1){
				$styleid = '';
				foreach($style_ids as $res){
					if($styleid == ''){
						$styleid = $res;
					}else{
						$styleid .= ','.$res;
					}
				}
				$productDb = D('product');
				$where2['id'] = array('IN', $styleid);
				if (isset($post['orderby']) && $post['orderby']) {
					$productDb->order($post['orderby']);
				} else {
					$productDb->order('new_product desc,product.sorts asc, product.id DESC');
				}
				$productDb->where($where2);
				$product_list = $productDb->select();

			}elseif($sc_value == 2){
				$colourid = '';
				foreach($colour_ids as $res){
					if($colourid == ''){
						$colourid = $res;
					}else{
						$colourid .= ','.$res;
					}
				}
				$productDb = D('product');
				$where2['id'] = array('IN', $colourid);
				if (isset($post['orderby']) && $post['orderby']) {
					$productDb->order($post['orderby']);
				} else {
					$productDb->order('new_product desc,product.sorts asc, product.id DESC');
				}
				$productDb->where($where2);
				$product_list = $productDb->select();
			}

			foreach ($product_list as $key => $product){

				$product_list[$key] = self::get_product_info($product['id']);
			}
		}else{
			//dump($productList);exit;
			$product_list = $productList;
			foreach ($product_list as $key => $product){
				//dump($product_list);exit;
				$product_v = self::get_product_info($product['id']);
				if(!empty($product_v)){
					$product_list[$key] = $product_v;
				}else{
					unset($product_list[$key]);
				}
			}
		}
		//dump($product_list);exit;

		return $product_list;
	}

	/**
	 * 随机商品列表
	 * @param string $type 随机别名,用于缓存标识
	 * @param array $filter 条件
	 * @param int $num 查询个数
	 */
	public static function get_random_product_list($type, $filter = array(), $num = 20)
	{
		$cacheId = md5(get_url()).$type;
		if(S($cacheId)){
			$productList = S($cacheId);
		}else{
			$cat_id = isset($filter['catid']) ? intval($filter['catid']) : null;
			if($cat_id){
				$categoryInfo = CategoryModel::get_category_info($cat_id);
				if(!$categoryInfo){
					$cat_id = null;
				}
				//分类分级过滤
				if($cat_id && isset($post['level'])){
					if ($post['level']==1){
						$cat_id = $categoryInfo['parentid'] ? $categoryInfo['parentid'] : $cat_id;
					}elseif($post['level']=='all'){
						$cat_id = null;
					}
				}
			}
			$filter['catid'] = $cat_id;
			$filter['orderby'] = 'rand()';
			$productList = self::get_product_list($filter, 0, $num);
			S($cacheId, $productList);
		}
		return $productList;
	}

	/**
	 * 获取关联商品信息
	 * @param int $pid 商品ID
	 * @param int $page 页数
	 * @param int $pageRows 页码
	 */
	public static function get_product_relation_list($pid, $page = 1, $pageRows = 0)
	{
		$productRelationList = array();
		$product_relation_db = D('product_relations');
		$product_relation_db->field('related_pid');
		$product_relation_db->join('product ON product.id = product_relations.related_pid');
		$product_relation_db->where(array('product_relations.pid'=>$pid));
		if($pageRows){
			$product_relation_db->page($page, $pageRows);
		}
		$productRelationList = $product_relation_db->select();
		if($productRelationList){
			foreach ($productRelationList as $key => $relation) {
				$productRelationList[$key] = self::get_product_info($relation['related_pid']);
			}
		}
		return $productRelationList;
	}

	/**
	 * 获取商品表最高价格和最低价格
	 * @param array $post 查询条件
	 */
	public static function get_product_price_limit($post = array())
	{
		//商品分类
		$cat_id = isset($post['catid']) ? intval($post['catid']) : null;
		if($cat_id){
			$categoryInfo = CategoryModel::get_category_info($cat_id);
			if(!$categoryInfo){
				$cat_id = null;
			}
			//获取子类集
			if($cat_id){
				$cat_id = CategoryModel::get_category_child_ids($cat_id);
			}
		}
		//推荐分类
		$recommend_id = isset($post['rid']) ? intval($post['rid']) : null;

		//筛选条件
		$where = array(
			'product.is_delete' => array('eq',0),
			'product.display' => 1,
			'product.is_sell' => isset($post['is_sell']) ? intval($post['is_sell']) : null,
			'product.catid' => array('IN', $cat_id),
			'product.brand_id' => isset($post['bid']) ? intval($post['bid']) : null,
		);
		foreach ($where as $key => $val){
			if(empty($val) && is_null($val)) unset($where[$key]);
		}
		if($recommend_id){
			$where['category_product.catid'] = $recommend_id;
		}
		$product_db = D('product');

		if(isset($post['attr']) && $post['attr']){
			$filter_attr_array = self::get_filter_attr($post['attr']);
			if($filter_attr_array){
				$key=0;
				foreach ($filter_attr_array as $attr_id => $attrValues){
					$where['pa'.$key.'.attr_id'] = $attr_id;
					if($attrValues['attr_value_id']){
						$where['pa'.$key.'.attr_value_id'] = $attrValues['attr_value_id'];
					}else{
						$where['pa'.$key.'.attr_value'] = $attrValues['attr_value'];
					}
					$product_db->join('product_attribute AS pa'.$key.' ON pa'.$key.'.product_id=product.id');
					$key++;
				}
				unset($key);
			}
		}

		$product_db->field('MAX(sell_price) high_price, MIN(sell_price) low_price');
		$product_db->where($where);
		if($recommend_id){
			$product_db->join('category_product ON category_product.pid = product.id');
		}
		$prices = $product_db->cache(true, C('DB_CACHE_TIME'))->find();
//		echo $product_db->getLastSql();exit;
		return $prices;
	}

	/**
	 * 取得商品最终使用价格
	 *
	 * @param   string  $goods_id      商品编号
	 * @param   string  $goods_num     购买数量
	 * @param   boolean $is_spec_price 是否加入规格价格
	 * @param   mix     $spec          规格ID的数组或者逗号分隔的字符串
	 * @param int $custom_type 定制类型
	 *
	 * @return  商品最终购买价格
	 */
	public static function get_final_price($pid, $qty = 1, $is_spec_price = false, $spec = array(), $custom_type = 0)
	{
		global $user;
		$rank_id = isset($user['rank_id']) ? $user['rank_id'] : 0;

		$final_price   = '0'; //商品最终购买价格
		$volume_price  = '0'; //商品优惠价格
		$promote_price = '0'; //商品促销价格
		$user_price    = '0'; //商品会员价格

		$low_price = 0;
		$product = self::get_product_info($pid);
		if($product)
		{
			//销售价格
			/*if($custom_type==0){
				$final_price = $product['sell_price'];
			}elseif($custom_type==1){
				$final_price = $product['custom_price'];
			}elseif($custom_type==2){
				$final_price = $product['advanced_price'];
			}*/

			if($product['attribute_type']==1){//正常价
				$final_price = $product['custom_price'];
			}elseif($product['attribute_type']==2){//定制价
				$final_price = $product['advanced_price'];
			}


			//批发价格
			$wholesale_price = PromotionModel::get_product_wholesale_price($pid, $qty, intval($rank_id));
			if ($wholesale_price)
			{
				$final_price = min($wholesale_price, $final_price);
			}
		}else{
			return 0;
		}
		//如果需要加入规格价格
		if ($is_spec_price)
		{
			if (!empty($spec))
			{
				$spec_price   = self::spec_price($spec);
				$final_price += $spec_price;
			}
		}

		//返回商品最终购买价格
		return $final_price;
	}

	/**
	 * 获得指定的规格的价格
	 *
	 * @access  public
	 * @param   mix     $spec   规格ID的数组或者逗号分隔的字符串
	 * @return  void
	 */
	public static function spec_price($spec)
	{

		if (!empty($spec))
		{
			$where['product_attr_id'] = array('IN', implode(',', $spec));
			$product_attribute = D('product_attribute');
			$attr_price = $product_attribute->where($where)->getField('SUM(attr_price) AS attr_price');
			$price = floatval($attr_price);
		}
		else
		{
			$price = 0;
		}

		return $price;
	}

	/**
	 * 获取扩展分类
	 * @param int $pid 商品ID号
	 */
	public static function get_other_cat_ids($pid)
	{
		$catIds = array();
		$cat_db = D('product_other_cat');
		$catIdsArray = $cat_db->field('catid')->where(array('pid' => $pid))->select();
		if($catIdsArray){
			foreach ($catIdsArray as $cat){
				$catIds[] = $cat['catid'];
			}
		}
		return $catIds ? join(',', $catIds) : false;
	}

	/**
	 * 获取扩展分类关联商品ID
	 * @param int $catids 商品分类ID
	 */
	public static function get_other_cat_pids($catids)
	{
		$pids = array();
		$cat_db = D('product_other_cat');
		$pidsArray = $cat_db->field('pid')->where(array('catid' => array('IN', $catids)))->cache(true, C('DB_CACHE_TIME'))->select();
		if($pidsArray){
			foreach ($pidsArray as $pro){
				$pids[] = $pro['pid'];
			}
		}
		return $pids ? join(',', $pids) : false;
	}

	/**
	 * 获得商品货号
	 * @param int $pid 产品ID号
	 * @return String
	 */
	public static function get_product_sn($pid)
	{
		$total_len = 12;
		$sn_pre = C('product_sn_pre');
		/**
		if(!empty($sn_pre))
		{
		if(strlen($sn_pre)>2)
		{
		$sn_pre = substr($sn_pre,0,2);
		}
		else if(strlen($sn_pre)==1)
		{
		$sn_pre = $sn_pre."0";
		}
		}
		else
		{
		$sn_pre = 'SN';
		}
		 **/
		if(empty($sn_pre)){
			$sn_pre = 'SN';
		}

		$sn_len = strlen($sn_pre);

		//判断加0的个数
		if(($total_len-$sn_len-strlen($pid))>0)
		{
			$j = $total_len-$sn_len-strlen($pid);
			for ($i = 0; $i < $j; $i++) {
				$sn_pre = $sn_pre."0";
			}
		}
		//组合货号
		$sn_pre = $sn_pre.$pid;
		return $sn_pre;
	}

	/**
	 * 生成产品唯一标识
	 * @param array post数据
	 * @return string
	 */
	public static function get_product_marking($post)
	{
		return md5(json_encode($post));
	}

	/**
	 * 更新产品信息
	 * @param array $post post数据
	 * @param int $pid 产品ID号
	 */
	public static function update_product_info($post, $pid = null)
	{
		$product_db = D('product');
		if($post['xianzhi'] > 0){
			$restriction = intval($post['restriction']);
		}else{
			$restriction = 0;
		}
		$data = array(
			'catid' => intval($post['catid']),
			'model_id' => intval($post['model_id']),
			'brand_id' => intval($post['brand_id']),
			'display' => intval($post['display']),
			'restriction' => $restriction,
			'sell_price' => floatval($post['sell_price']),
			'custom_price' => floatval($post['custom_price']),
			'advanced_price' => floatval($post['advanced_price']),
			'market_price' => floatval($post['market_price']),
			'cost_price' => floatval($post['cost_price']),
			'yufu_price' => floatval($post['yufu_price']),
			'sell_min' => intval($post['sell_min']),
			'sell_max' => intval($post['sell_max']),
			'weight' => floatval($post['weight']),
			'stock' => intval($post['stock']),
			'img' => trim($post['img']),
			'small_img' => trim($post['small_img']),
			'list_img' => trim($post['list_img']),
			'bg_img' => isset($post['bg_img']) ? trim($post['bg_img']) : '',
			'path_alias' => trim($post['path_alias']),
			'template' => trim($post['template']),
			'visit' => intval($post['visit']),
			'end_time' => time(),
			'yushou_start_time' => strtotime(trim($post['yushou_start_time'])),
			'yushou_end_time' => strtotime(trim($post['yushou_end_time'])),
			'weikuan_time' => strtotime(trim($post['weikuan_time'])),
			'listorder' => intval($post['listorder']),
			'rank_integral' => (isset($post['rank_integral']) && $post['rank_integral']!=-1) ? intval($post['rank_integral']) : -1,
			'integral' => (isset($post['integral']) && $post['integral']!=-1) ? intval($post['integral']) : -1,
			'suppliers_id' => intval($post['suppliers_id']),
			'is_delete' => 0,
			'issend' => 0,
			'designer_id' => isset($post['designer_id']) ? intval($post['designer_id']) : 0,
			'designer_product_id' => isset($post['designer_product_id']) ? intval($post['designer_product_id']) : 0,
			'product_up' => isset($post['product_up']) ? intval($post['product_up']) : 0,
			'product_down' => isset($post['product_down']) ? intval($post['product_down']) : 0,
			'is_sell' => isset($post['is_sell']) ? $post['is_sell'] : 0,
		);
		if($pid){
			$product_db->where(array('id' => $pid))->save($data);
		}else{
			$data['start_time'] = time();
			$data['product_marking'] = self::get_product_marking($data);
			$pid = $product_db->add($data);
		}
		//更新货号
		$sn = trim($post['sn']);
		if(empty($sn)){
			$sn = self::get_product_sn($pid);
		}else{
			$count = $product_db->where(array('sn' => $sn, 'id' => array('neq',$pid)))->count();
			if($count){
				$sn .= '-'.$pid;
			}
		}
		$product_db->where(array('id' => $pid))->save(array('sn' => $sn));

		//删除缓存
		self::delete_product_cache($pid);
		return $pid;
	}

	/**
	 * 更新产品内容详细
	 * @param array $post post数据
	 * @param int $pid 产品ID号
	 */
	public static function update_product_items($post, $pid)
	{
		$product_items_db = D('product_items');
		$product_items_db->where(array('product_id' => $pid))->delete();

		$languageList = SiteModel::get_language_list();
		foreach($languageList as $lang){
			$language_id = $lang['id'];
			if($post[$language_id]['name']){
				$data = array(
					'product_id' => $pid,
					'language_id' => $language_id,
					'name' => trim($post[$language_id]['name']),
					'summary' => trim($post[$language_id]['summary']),
					'description' => $post[$language_id]['description'],
					'meta_title' => trim($post[$language_id]['meta_title']),
					'meta_keywords' => trim($post[$language_id]['meta_keywords']),
					'meta_description' => trim($post[$language_id]['meta_description']),
				);
				$product_items_db->add($data);
			}
		}
	}

	/**
	 * 更新产品的访问量
	 * @param int $pid	产品ID
	 */
	public static function update_product_visit($pid)
	{
		$product_db = D('product');
		$productInfo = self::get_product_info($pid);
		if(!$productInfo)return false;
		$product_db->where('id='.$pid)->setInc('visit');
	}

	/**
	 * 列表页属性与产品关联列表
	 * @param int $attr_id 属性ID
	 * @param string $catIds 多个分类ID联接字符串 12,13,14
	 * @return array
	 */
	public static function get_attribute_search_product_list($attr_id, $catIds)
	{
		$where = array(
			'product_attribute.attr_id' => $attr_id,
			'product.catid' => array('in', $catIds),
			'product.is_sell' => '1',
			'product.display' => 1,
			'product.is_delete' => 0,
		);
		$product_attribute_db = D('product_attribute');
		$product_attribute_db->field('product_attribute.attr_id,product_attribute.attr_value_id,MIN(product_attribute.product_attr_id ) AS goods_id,product_attribute.attr_value');
		$product_attribute_db->join('product ON product.id=product_attribute.product_id');
		$product_attribute_db->where($where);
		$product_attribute_db->group('product_attribute.attr_value_id');
		$attr_list = $product_attribute_db->cache(true,C('DB_CACHE_TIME'))->select();
		return $attr_list ? $attr_list : array();
	}

	/**
	 * 更新顶踩次数
	 * @param int $pid 产品ID
	 * @param string $type up/down
	 */
	public static function update_product_up_down($pid, $type='up')
	{
		$product_db = D('product');
		$productInfo = self::get_product_info($pid);
		if(!$productInfo)return false;
		$field = $type=='up' ? 'product_up' : 'product_down';
		$product_db->where('id='.$pid)->setInc($field);
//		self::delete_product_cache($pid);
	}

	/**
	 * 获取顶踩次数
	 * @param int $pid 产品ID
	 */
	public static function get_product_up_down($pid,$did=0)
	{

		if($did>0){
			$designer_product_db = D('designer_product');
			$up_down = $designer_product_db->field('designer_up,designer_down')->where('id='.$did)->find();
		}else{
			$product_db = D('product');
			$productInfo = self::get_product_info($pid);
			if(!$productInfo)return false;
			$up_down = $product_db->field('product_up,product_down')->where('id='.$pid)->find();
		}

		return is_array($up_down) ? $up_down : array();
	}

	/**
	 * 删除产品缓存
	 * @paramint $pid 产品ID号
	 */
	public static function delete_product_cache($pid)
	{
		$languageList = SiteModel::get_language_list();
		foreach($languageList as $language_id => $language_name){
			$cacheId = 'product_'.$pid.'_'.$language_id;
			S($cacheId, NULL);
		}
	}

	/**
	 * 更新晒单信息
	 * @param array $post post数据
	 * @param int $pid 产品ID号
	 */
	public static function updateShaidanInfo($post, $pid = null)
	{
		global $user;

		$shaidan_disabled = C('shaidan_disabled');
		if($shaidan_disabled > 0){
			$disabled = 0;
		}else{
			$disabled = 1;
		}
		$product_db = D('shaidan');
		$data = array(
			'product_id' => intval($post['product_id']),
			'title' 	 => $post['title'],
			'content' 	 => $post['content'],
			'time' 		 => time(),
			'user_id' 	 => $user['id'],
			'username' 	 => $user['username'],
			'ip' 		 => get_client_ip(),
			'disabled' 	 => $disabled,
		);
		if($pid){
			$product_db->where(array('id' => $pid))->save($data);
		}else{
			$pid = $product_db->add($data);
		}

		//送相应的积分
		if($shaidan_disabled == 0){
			$order_shaidan_jifen = C('order_shaidan_jifen');
			if($order_shaidan_jifen){
				UserModel::log_account_change($user['id'], 0, 0, $order_shaidan_jifen, $order_shaidan_jifen, L('Bask in single get ').$order_shaidan_jifen.L('points, bask in single products for: ').$post['title'], UserModel::ACT_SHAIDAN);
			}
		}
		//删除缓存
		//self::deleteShaidanCache($pid);
		return $pid;
	}

	/**
	 * 删除产品关联图片
	 * @param int $pid 产品ID号
	 */
	public static function deleteShaidanPhotoRelation($pid)
	{
		//TODO没有删除图片
		$product_photo_relation_db = D('shaidan_photo_relation');
		$product_photo_relation_db->where('sid='.$pid)->delete();
	}

	/**
	 * 获取产品晒单列表
	 * @param int $pid 产品ID
	 */
	public static function get_shaidan_list($pid,$disabled)
	{
		$where = array(
			'product_id' => $pid,
			'disabled' => $disabled,
		);
		$sd_db = D('shaidan');
		$sd_db->field('id,title,user_id,product_id,content,time');
		$sd_db->where($where);
		$shaidanList = $sd_db->order('id DESC')->select();
		return $shaidanList;
	}

	/**
	 * 晒单关联图片
	 * @param int $pid 产品ID
	 */
	public static function getShaidanPhotoList($pid)
	{
		//print_r($pid);
		$product_photo_db = D('product_photo');
		$files = $product_photo_db->field('product_photo.*')->join('shaidan_photo_relation AS pr ON pr.fid = product_photo.fid')->where('pr.sid='.$pid)->select();
		foreach ($files as &$file){
			$file['thumb'] = dirname($file['img']).'/thumb_'.basename($file['img']);
		}
		return $files;
	}

	/**
	 * 统计用户晒单数量
	 * @param int $pid 产品ID
	 * @return array
	 */
	public static function get_shaidan_count($uid)
	{
		if($uid){
			//统计晒单
			$sd_db = D('shaidan');
			$sdList = $sd_db->field('product_id')->where('user_id='.$uid.'')->order('id DESC')->select();
			$shaidan_count = count($sdList);

			//统计已购买的商品
			$order_db = D('orders');
			$ordersList = $order_db->field('id,start_time')->where('order_status=2 AND user_id='.$uid.'')->order('id DESC')->select();
			foreach ($ordersList as $v){
				$MyProduct = OrderModel::get_order_product_list($v['id']);
				//echo count($MyProduct)."<br>";
				for($i=0;$i<count($MyProduct);$i++){
					$v['id'] = $MyProduct[$i]['product_id'];
					$MyProductList[$v['id']]['name'] = $MyProduct[$i]['product_name'];
					$MyProductList[$v['id']]['time'] = $v['start_time'];
					$MyProductList[$v['id']]['id'] = $v['id'];
				}

			}

			$number = count($MyProductList) - $shaidan_count;

		}
		return $number;
	}

	/**
	 * 获取商品价格变动信息
	 * @param int $pid 商品ID号
	 */
	public static function product_price_changes($pid)
	{
		if($pid){
			$product_price_changes_db = D('product_price_changes');
			$info = $product_price_changes_db->where( array('product_id' => $pid) )->find();
		}
		return $info;
	}
	/**
	 * 获取优惠套餐活动商品列表
	 * @param array $pid 商品ID数组
	 * @return array
	 */
	public static function get_product_package_list($pid, $lang_id=0)
	{
		if($lang_id){
			$language_id = $lang_id;
		}else{
			global $language_id;
		}
		$default_product_info = array();
		if(is_array($pid)){
			$cachelist = array();
			foreach($pid  as $k => $v){
				foreach ($v as $k1 => $v1){
					$cacheId = 'product_'.$v1.'_'.$language_id;
					$cache = S($cacheId);
					if($cache){//从缓存读取商品信息
						if($k1 == 'suit_id'){
							$cachelist[$k]['suit_id'] = $cache;
							continue;
						}
						if($k1 == 'shirt_id'){
							$cachelist[$k]['shirt_id'] = $cache;
							continue;
						}
						if($k1 == 'accessories_id'){
							$cachelist[$k]['accessories_id'] =$cache;
							continue;
						}
					}else{//如果缓存读取失败，重新读取商品信息
						if($k1 == 'suit_id'){
							$cachelist[$k]['suit_id'] =  self::get_product_info($v1,$language_id);
							continue;
						}
						if($k1 == 'shirt_id'){
							$cachelist[$k]['shirt_id'] = self::get_product_info($v1,$language_id);
							continue;
						}
						if($k1 == 'accessories_id'){
							$cachelist[$k]['accessories_id'] = self::get_product_info($v1,$language_id);
							continue;
						}

					}
				}
			}
			return $cachelist;
		}else{
			return false;
		}
	}

	//自定义系列使用
	public static function get_product_collection_list($pid, $lang_id=0)
	{
		if($lang_id){
			$language_id = $lang_id;
		}else{
			global $language_id;
		}
		$default_product_info = array();
		if(is_array($pid)){
			$cachelist = array();
			foreach($pid  as $k => $v){
				$v = intval($v);
				$cacheId = 'product_'.$v.'_'.$language_id;
				//dump($cacheId);exit;
				$cache = S($cacheId);
				if($cache){
					$cachelist[] =$cache;
				}else{
					$cachelist[] = self::get_product_info($v,$language_id);
				}
			}
			foreach ($cachelist as $key => $product) {
				if($product['display'] == 0||$product['catid']==2172){//零剪面料不显示
					unset($cachelist[$key]);
				}
			}
			return $cachelist;
		}else{
			$cacheId = 'product_'.$pid.'_'.$language_id;
			$cache = S($cacheId);
			if($cache){
				$product = $cache;
			}else{
				$product = self::get_product_info($pid,$language_id);
			}
			if($product && $product['display'] == 0){
				return null;
			}
			return $product;
		}
	}

	/**
	 * 记录定制统计
	 * @param array $type 类型
	 * @param array $post 数据
	 */
	public static function set_ipcount($type, $post)
	{

		global $user;
		$ip  = get_client_ip();
		$sid = $user['sid'];

		if($type == 'add'){   //写入新记录

			//修改定制时取原先的数据
			if(intval($post['cartid']) > 0){
				$where = array(
					'cartid' => $post['cartid'],
				);
				$get_id = D('ipcount')->where($where)->order('id desc')->getField('id');
				if($get_id){
					return $get_id;
				}
			}

			$data = array(
				'ip' => $ip,
				'sid' => $sid,
				'pid' => $post['pid'],
				'custom' => $post['custom'],
				'custom_time' => time(),
			);
			$get_id = D('ipcount')->add($data);
			return $get_id;
		}else if($type == 'add_option'){  //是否点击了more_option
			$where = array(
				'id'          => $post['id'],
				'more_option' => 0,
			);
			$data = array(
				'more_option' => 1,
			);
			D('ipcount')->where($where)->save($data);
		}else if($type == 'add_cart'){  //当加入购物车时写入cartid
			$where = array(
				'ip' => $ip,
				'sid' => $sid,
				'pid' => $post['pid'],
			);
			$get_id = D('ipcount')->where($where)->order('id desc')->getField('id');
			if($get_id > 0){
				D('ipcount')->where(array('id'=>$get_id))->save(array('cartid'=>$post['cartid']));
			}
		}else if($type == 'add_order'){ //当生成订单时写入orderid和orderitemid
			$where = array(
				'cartid' => $post['cartid'],
			);
			$data = array(
				'orderid'     => $post['orderid'],
				'orderitemid' => $post['orderitemid'],
			);
			D('ipcount')->where($where)->save($data);
		}

	}
	//商品详情页面推荐
	public static function ProductRecommend($model_id,$pid = null){

		$qtysRes = self::recommend_qtys($model_id,$pid);
		$productId = array();
		foreach($qtysRes as $v){
			$productId[] = $v['product_id'];
		}

		if(count($productId) < 10){
			$sql = 'SELECT product.id from product as product
					where product.display  = 1 and (product.model_id='.$model_id.') and (product.id !='.$pid.') ORDER BY visit DESC limit 0,'.(10-count($productId));
			$res = M()->query($sql);
			foreach ($res as $v) {
				$productList[] = $v;
			}
			return $productList;
		}else{
			foreach($productId as $k=>$v){
				if($pid == $v){
					continue;
				}
				$product_data[$k]['id']= $v;
			}
			return $product_data;
		}
	}
	public static function recommend_qtys($model_id,$pid = 0){

		$sql = "SELECT items.product_id,sum(qty) as qtys from orders_items as items
		        LEFT JOIN orders as orders on(items.order_id = orders.id) 
		        where items.product_id in(select product.id from product as product
				where product.display  = 1 and (product.model_id='{$model_id}') and (product_id !={$pid}) ) and orders.payment_status = 1 
				GROUP BY items.product_id ORDER BY qtys DESC limit 0,10";
		//dump($sql);die;
		$res = M()->query($sql);
		return $res;
	}
	/**
	 * 产品搜索记录
	 * @param array $post 会话ID
	 */
	public static function insertSearchHistory($post)
	{
		global $user;
		$user_id = 0;
		if(isset($user['id']) && $user['id']){
			$user_id = $user['id'];
		}
		$data = array(
			'keyword' => $post['keyword'],
			'user_id' => $user_id,
			'sid' => $user['sid'],
			'ip' => get_client_ip(),
			'add_time' => time(),
			'result' => $post['result'],
		);

		$search_db = D('search');
		$searchHistory = $search_db->add($data);

		return $searchHistory;
	}
	/**
	 * 产品搜索历史
	 * @param int $num 取几条记录
	 * @return array
	 */
	public static function searchHistory($num = 5)
	{
		global $user;
		$where = array(
			'result' => array('gt', 0),
		);
		if(isset($user['id']) && $user['id']){
			$_complex['user_id'] = $user['id'];
			$_complex['sid']  = $user['sid'];
			$_complex['_logic'] = 'or';
			$where['_complex'] = $_complex;
		}else{
			$where['sid'] = $user['sid'];
		}

		$search_db = D('search');
		$searchHistory = $search_db->field('distinct(keyword)')->where($where)->order('id desc')->limit('0,'.$num)->select();

		return $searchHistory;
	}


	/**
	 *写入浏览记录商品
	 * @param int $pid 商品id
	 */
	function insertBrowsingHistoryProduct($pid){
		global $user;
		if (isset($user['id']) && $user['id']) {
			$where['user_id'] = $user['id'];
		}else{
			$where['user_id'] = 0;
			$where['sid'] = $user['sid'];
		}
		$where['pid'] = $pid;
		$browsing_history_db = D('browsing_history');

		$hid = $browsing_history_db->where($where)->getField('id');
		if($hid){
			$browsing_history_db->where(array('id'=>$hid))->save(array('update_time'=>time()));
		}else{
			$data = array(
				'sid' => $user['sid'],
				'user_id' => isset($user['id']) ? $user['id'] : 0,
				'pid' => intval($pid),
				'update_time' => time(),
			);
			$last_id = $browsing_history_db->add($data);
		}
	}

	/**
	 *获取浏览记录
	 */
	public static function getBrowsingHistory()
	{
		global $user;
		if (isset($user['id']) && $user['id']) {
			$where['user_id'] = $user['id'];
		}else{
			$where['user_id'] = 0;
			$where['sid'] = $user['sid'];
		}
		$browsing_history_db = D('browsing_history');
		$browsing_history = $browsing_history_db->where($where)->order('update_time DESC')->limit('0,10')->select();

		return $browsing_history;
	}

	/**
	 *获取浏览记录中商品列表
	 */
	public static function getBrowsingHistoryProduct()
	{
		global $language_id;
		$browsingHistory = self::getBrowsingHistory();
		$historyProduct = array();
		foreach ($browsingHistory as $history) {
			$historyProduct[] = ProductModel::get_product_collection_list($history['pid'],$language_id);
		}
		return $historyProduct;
	}

	/**
	 * 合并浏览记录
	 * @param string $sid 会话ID
	 */
	public static function mergeBrowsingHistory($sid = null)
	{
		global $user;
		if (!session('user_id')) {
			return false;
		}
		if (!isset($sid)) {
			$sid = $user['sid'];
		}
		$browsing_history_db = D('browsing_history');
		$affected = $browsing_history_db->where(array('sid' => $sid,'user_id'=>array('eq',0)))->save( array('user_id' => session('user_id')));
		return (boolean)$affected;
	}
	/**
	 * 获取鞋子尺码
	 *
	 * */
	public static function get_shoes_size_data($max_size,$min_size,$del_size=null){
		if(cache("get_shoes_size_data")){
			$show_data = cache("get_shoes_size_data");
		}else{
			$shoes_size_db=D("shoes_size_data");
			$shoes_size_db->order('cn_size');
			$shoes_size_data=$shoes_size_db->where('cn_size >='.$min_size." and cn_size<=".$max_size)->select();
			if($del_size&&$del_size>$min_size&&$del_size<$max_size){
				$del_size_arr=explode(",",$del_size);
			}
			foreach ($shoes_size_data as $k=>$v){
				if(!in_array($v['cn_size'],$del_size_arr)){
					$show_data[]=$v['cn_size'];
				}
			}
			cache('get_shoes_size_data', $show_data);
			unset($shoes_size_data);
		}
		return  $show_data;
	}

}